﻿//#region 地理编码
//使用地理编码，请执行doGeoCoder函数
//如有疑问请访问文档说明：http://developer.baidu.com/map/webservice-geocoding.htm#.E6.8E.A5.E5.8F.A3.E5.8F.82.E6.95.B6
/*
使用示例
var geo = new Geocoder();
geo.getPoint(
"广州市越秀区五羊新城寺右二马路16号",
"广州市",
"geo",
function (e) {
alert(e);
});
*/
var Geocoder = function () {
    //#region 服务地址
    var SAMPLE_ADVANCED_POST = 'http://api.map.baidu.com/geocoder/v2/?ak=您的密钥&output=json';
    //#endregion

    //#region 变量声明
    var advancedOptions = '';
    var _fun = null;
    //#endregion

    //#region 地址组装
    /**
    * 
    * address  地址
    * cityname 城市名
    * objStr   对象实例化的变量名,或者是说对象名
    * fun      外部函数
    */
    function showOptionsURL(address, cityname, objStr, fun) {
        advancedOptions = SAMPLE_ADVANCED_POST;
        advancedOptions += "&address=" + address;
        advancedOptions += "&city=" + cityname;
        if (objStr != "" && objStr != null) {
            advancedOptions += "&callback=" + objStr + ".renderOption";
            _fun = fun;
        }
        else {
            throw new Error("缺少objStr参数");
        }
    };
    //#endregion

    //#region 执行请求
    /**
    * 
    * address  地址
    * cityname 城市名
    * objStr   对象实例化的变量名,或者是说对象名
    * fun      外部函数
    */
    this.getPoint = function (address, cityname, objStr, fun) {
        var script = document.createElement('script');
        script.type = 'text/javascript';
        showOptionsURL(address, cityname, objStr, fun);
        var key;
        if (new Date().getSeconds() % 2 == 1)
            key = "32a68d1bcf1edc1b37d3bb055beac284";
        else
            key = "KjPkYUoqNxcGkZ0NyIGSwqH2";

        var newURL = advancedOptions.replace('您的密钥', key);
        script.src = newURL;
        document.body.appendChild(script);
    };
    //#endregion

    //#region 结果接收
    this.renderOption = function (response) {
        if (_fun) {
            _fun(response);
        }
    }
    //#endregion
}

//#endregion